package VectorApproach;

import java.awt.Color;
import java.awt.Graphics2D;

import XmlLoader.Position;

public class ScreenGrid {
	
	Grid[][] listGrid = null;
	int cubeLen = 0;
	int totalClusterNum = 0;
	public ScreenGrid(int cubeLen, int length, int width, int totalClusterNum) {
		this.cubeLen = cubeLen;
		this.totalClusterNum = totalClusterNum;
		this.listGrid = new Grid[width/cubeLen][length/cubeLen];
		int indexRow = 0, indexCol = 0;
		while(indexRow < this.listGrid.length) {
			indexCol = 0;
			while(indexCol < this.listGrid[0].length) {
				this.listGrid[indexRow][indexCol] = new Grid(new Position(cubeLen*indexCol, cubeLen*indexRow), cubeLen, totalClusterNum);
				indexCol = indexCol + 1;
			}
			indexRow = indexRow + 1;
		}
	}
	
	public void ACT001_addNewTraj(TrajVector traj, int clusterID) {
		listGrid[traj.startPos.y/cubeLen][traj.startPos.x/cubeLen].ACT001_addNewTraj(traj, clusterID);
		listGrid[traj.getEndPos().y/cubeLen][traj.getEndPos().x/cubeLen].ACT001_addNewTraj(traj, clusterID);
		
		double dt = traj.ACT002_getVt(cubeLen);
		double dx = traj.eachVector.x * dt;
		double dy = traj.eachVector.y * dt;
		Position pos = new Position((int)(traj.startPos.x + dx), (int)(traj.startPos.y + dy));
		if(dx > 0) {
			while(pos.x < traj.getEndPos().x && ((dy >= 0 && pos.y < traj.getEndPos().y) || (dy < 0 && pos.y > traj.getEndPos().y))) {
				listGrid[pos.y/cubeLen][pos.x/cubeLen].ACT001_addNewTraj(traj, clusterID);
				pos.x = (int)(Math.round(pos.x + dx));
				pos.y = (int)(Math.round(pos.y + dy));
			}
		}
		else {
			while(pos.x > traj.getEndPos().x && ((dy >= 0 && pos.y < traj.getEndPos().y) || (dy < 0 && pos.y > traj.getEndPos().y))) {
				listGrid[pos.y/cubeLen][pos.x/cubeLen].ACT001_addNewTraj(traj, clusterID);
				pos.x = (int)(pos.x + dx);
				pos.y = (int)(pos.y + dy);
			}
		}
	}
	
	public void ACT002_draw(Graphics2D g) {
		int indexRow = 0, indexCol = 0;
		while(indexRow < this.listGrid.length) {
			indexCol = 0;
			while(indexCol < this.listGrid[0].length) {
				Grid grid = this.listGrid[indexRow][indexCol];
				int clusterID = grid.GET001_maxClusterID();
				if(clusterID != -1) {
					this.ACT003_drawGrid(grid, Application.ImageGenerator.listColor[clusterID], g);
				}
				indexCol = indexCol + 1;
			}
			indexRow = indexRow + 1;
		}
	}
	
	public void ACT003_drawGrid(Grid grid, Color color, Graphics2D g) {
		int indexX = grid.pos.x, indexY = grid.pos.y;
		g.setColor(color);
		while(indexX < grid.pos.x + this.cubeLen) {
			indexY = grid.pos.y;
			while(indexY < grid.pos.y + this.cubeLen) {
				g.drawLine(indexX, indexY, indexX, indexY);
				indexY = indexY + 1;
			}
			indexX = indexX + 1;
		}
	}
	
	public void ACT004_postprocess(double mainAngle) {
		
	}
}
